package test02;

// SwingLoginView.java - Swing实现的视图
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

/**
 * View实现 - 负责用户界面展示
 */
public class SwingLoginView extends JFrame implements LoginView {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JLabel messageLabel;

    public SwingLoginView() {
        initializeUI();
    }

    private void initializeUI() {
        setTitle("简易登录系统 - MVC架构");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(350, 250);
        setLocationRelativeTo(null);
        setResizable(false);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建表单面板
        JPanel formPanel = new JPanel(new GridLayout(3, 2, 10, 10));

        // 用户名组件
        formPanel.add(new JLabel("用户名:"));
        usernameField = new JTextField();
        formPanel.add(usernameField);

        // 密码组件
        formPanel.add(new JLabel("密码:"));
        passwordField = new JPasswordField();
        formPanel.add(passwordField);

        // 消息标签
        formPanel.add(new JLabel("状态:"));
        messageLabel = new JLabel("请输入用户名和密码");
        messageLabel.setForeground(Color.BLUE);
        formPanel.add(messageLabel);

        // 登录按钮
        loginButton = new JButton("登录");

        // 添加组件到主面板
        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(loginButton, BorderLayout.SOUTH);

        add(mainPanel);
    }

    @Override
    public String getUsername() {
        return usernameField.getText().trim();
    }

    @Override
    public String getPassword() {
        return new String(passwordField.getPassword());
    }

    @Override
    public void showSuccess(String message) {
        messageLabel.setForeground(Color.GREEN);
        messageLabel.setText(message);
        JOptionPane.showMessageDialog(this, message, "登录成功", JOptionPane.INFORMATION_MESSAGE);
    }

    @Override
    public void showError(String message) {
        messageLabel.setForeground(Color.RED);
        messageLabel.setText(message);
        passwordField.setText(""); // 清空密码框
        passwordField.requestFocus(); // 焦点回到密码框
    }

    @Override
    public void clearFields() {
        usernameField.setText("");
        passwordField.setText("");
        messageLabel.setForeground(Color.BLUE);
        messageLabel.setText("请输入用户名和密码");
    }

    @Override
    public void setLoginListener(ActionListener listener) {
        loginButton.addActionListener(listener);
        // 为文本框添加回车键监听
        usernameField.addActionListener(listener);
        passwordField.addActionListener(listener);
    }

    public void setVisible(boolean visible) {
        super.setVisible(visible);
        if (visible) {
            usernameField.requestFocus(); // 显示时焦点在用户名框
        }
    }
}